#include <iostream>
#include <string>
#include <cstdio>
#include <unistd.h>
#include <pthread.h>

using namespace std;

int x = 100; //主线程定义的全局变量，新线程可以看到

void show(const string &threadName)
{
    cout << threadName << ", pid: " << getpid() << " global var x= " << x << endl
         << endl;
}

void *threadRun(void *args)
{
    const string threadName = (char *)args;
    while (true)
    {
        show(threadName);
        sleep(1);
    }
}
#define THREADNUM 5
int main()
{
    // typedef unsigned long int pthread_t;
    pthread_t tid[THREADNUM];

    char threadName[64];
    for (int i = 0; i < THREADNUM; i++)
    {
        snprintf(threadName, sizeof threadName, "%s%d", "thread", i + 1);
        pthread_create(tid + i, nullptr, threadRun, (void *)threadName);
        sleep(1); // 缓解传参的bug
    }

    while (true)
    {
        cout << "main thread, pid: " << getpid() << endl;
        sleep(3);
    }
}